package com.bst.etl.utils;
import com.alibaba.druid.pool.DruidDataSource;
import com.bst.system.framework.datasource.DynamicDataSource;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class DorisSaveCreateSqlUtil {
        private static final String OUTPUT_FILE = "doris_table_backup.sql";
        public static void saveCreateSql(DruidDataSource db) {
            BufferedWriter writer = null;
            Connection connection = null;
            Statement statement = null;
            ResultSet resultSet = null;
            try {
                connection = db.getConnection();

                // 创建Statement对象
                statement = connection.createStatement();
                // 获取所有表的名称
                resultSet = statement.executeQuery("SHOW TABLES");
                List<String> tables = new ArrayList<>();
                while (resultSet.next()) {
                    String tableName = resultSet.getString(1);
                    tables.add(tableName);
                }
                resultSet.close();
                // 打开文件写入器
                writer = new BufferedWriter(new FileWriter(OUTPUT_FILE));
                for (String tableName : tables) {
                    String showCreateTable = "SHOW CREATE TABLE " + tableName;
                    resultSet = statement.executeQuery(showCreateTable);
                    if (resultSet.next()) {
                        String createTableSql = resultSet.getString(2);
                        writer.write(createTableSql);
                        writer.newLine();
                    }
                    resultSet.close();
                }
                System.out.println("Backup completed successfully!");

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                // 关闭资源
                try {
                    if (writer != null) writer.close();
                    if(resultSet!=null) resultSet.close();
                    if (statement != null) statement.close();
                    if (connection != null) connection.close();
                } catch (IOException | SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
